<template>
    <view class="income-record pd-v-24">


        <view class="income-record__header">
            <u--form
                labelWidth="80"
                labelPosition="left"
                :model="form"
            >
                <view class="border8 pd-l-24 bg-white mr-t-20">
                    <u-form-item
                        label="状态"
                        prop="status"
                        borderBottom
                        @click="showPicker = true"
                    >
                        <u--input
                            v-model.trim="form.status"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请选择状态"
                            readonly
                            suffixIcon="arrow-down"
                            :suffixIconStyle="{marginRight:'18rpx'}"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="时间"
                        prop="timeRange"
                        borderBottom
                        @click="showDatePicker"
                    >
                        <u--input
                            v-model.trim="form.timeRange"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请选择日期"
                            suffixIcon="calendar"
                            readonly
                            :suffixIconStyle="{marginRight:'12rpx',fontSize:'50rpx'}"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="所属商户"
                        prop="merchantId"
                        borderBottom
                        @click="showShopPicker = true"
                    >
                        <u--input
                            v-model.trim="form.merchantId"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请选择所属商户"
                            readonly
                            suffixIcon="arrow-down"
                            :suffixIconStyle="{marginRight:'18rpx'}"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="所属门店"
                        prop="merchantId"
                        borderBottom
                        @click="storeShowPicker = true"
                    >
                        <u--input
                            v-model.trim="form.storename"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请选择所属门店"
                            readonly
                            suffixIcon="arrow-down"
                            :suffixIconStyle="{marginRight:'18rpx'}"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        v-if="store?.user?.userInfo1?.roleType == 1"
                        label="合作伙伴"
                        prop="partner"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.partner"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入合作伙伴"
                        ></u--input>
                    </u-form-item>
                </view>
            </u--form>

            <view class="flex flex-center mr-t-20">
                <view class="income-total flex-1 pd-v-16 pd-h-16  border8 position-r">
                    <image src="@/static/my_income.png" class="total-bg position-a full-w full-h" mode="widthFix"></image>
                    <view class="color-main font28 lh-40 position-r">我的收益统计</view>
                    <view class="color-main font32 lh-50 mr-t-8 bold position-r">¥{{ store?.user?.userInfo1?.roleType == 1 ? agentAmount : store?.user?.userInfo1?.roleType == 2 ? partnerAmount : 0 }}</view>
                </view>
                
                <view class="shop-total flex-1 pd-v-16 pd-h-16 mr-v-16 border8 position-r">
                  <image src="@/static/shop_income.png" class="total-bg position-a full-w full-h" mode="widthFix"></image>
                    <view class="color-shop font28 lh-40 position-r">商户收益统计</view>
                    <view class="color-shop font32 lh-50 mr-t-8 bold position-r">¥{{ merchantAmount }}</view>
                </view>
                
                <view class="income-total flex-1 pd-v-16 pd-h-16 border8 position-r">
                    <image src="@/static/my_income.png" class="total-bg position-a full-w full-h" mode="widthFix"></image>
                    <view class="color-main font28 lh-40 position-r">门店收益统计</view>
                    <view class="color-main font32 lh-50 mr-t-8 bold position-r">¥{{  storeAmount }}</view>
                </view>
            </view>
        </view>
          
        
        <view class="income-record__body">
            <view class="pd-v-24 pd-h-24 border8 bg-white mr-t-16" v-for="(item,index) in list" :key="'iii'+index">
                <view class="flex mr-b-20 flex-center">
                    <view class="flex-1 flex">
                        <view class="flex flex-center font24 lh-28 w160 color-info">
                            我的收益
                        </view>
                        <view class="flex-1 font24 lh-28 mr-l-20 color-main">
                            ￥{{ store?.user?.userInfo1?.roleType == 1 ? item.agentIncome : store?.user?.userInfo1?.roleType == 2 ? item.partnerIncome : '-'}}
                        </view>
                        
                    </view>
                    <view class="pd-v-16 border8 font20 lh-28 color-main">
                      <text v-if="item.status == 0" class="color-orange font20 lh-28">待结算</text>
                      <text v-if="item.status == 1" class="color-info font20 lh-28">已结算</text>
                    </view>
                      
                </view>

                <!-- <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-info ">
                        我的收益
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-main">
                        ￥{{item.agentIncome}}
                    </view>
                </view> -->
                <view class="flex mr-b-20" v-if="store?.user?.userInfo1?.roleType == 1">
                    <view class="font24 lh-28 w160 color-info " >
                        合作伙伴收益
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-main">
                        ￥{{item.partnerIncome || '-'}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-info ">
                        商户收益
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-main">
                        ￥{{item.merchantIncome}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-info ">
                        时间
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-default">
                        {{item.createTime}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-note ">
                        订单编号
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-note">
                       {{item.orderNumber}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-note ">
                        订单金额
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-main">
                       ￥{{item.orderPrice}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-note ">
                        门店名称
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-note">
                        {{item.storeName}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-note ">
                        设备信息
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-note">
                        {{item.deviceInfo}}
                    </view>
                </view>
                <view class="flex mr-b-20">
                    <view class="font24 lh-28 w160 color-note ">
                        所属商户
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-note">
                        {{item.merchantName}}
                    </view>
                </view>
                <view class="flex mr-b-20" v-if="store?.user?.userInfo1?.roleType == 1">
                    <view class="font24 lh-28 w160 color-note ">
                        所属合作伙伴
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-note">
                        {{item.partnerName || '-'}}
                    </view>
                </view>
                <view class="flex mr-b-20" v-if="store?.user?.userInfo1?.roleType == 2">
                    <view class="font24 lh-28 w160 color-info " >
                        所属上级
                    </view>
                    <view class="flex-1 font24 lh-28 mr-l-20 color-note">
                        {{item.agentName || '-'}}
                    </view>
                </view>
                  
                  
            </view>

              
        </view>

        <u-calendar  
            mode="range"
            :defaultDate="calendar.defaultDate"
            :maxDate="calendar.maxDate"
            :minDate="calendar.minDate"
            :monthNum="calendar.monthNum" 
            :show="show" 
            @close="show = false;" 
            @confirm="timeConfirm">
        </u-calendar>

        <u-picker :show="showPicker" :columns="columns" keyName="label" :closeOnClickOverlay="true" @cancel="showPicker = false" @close="showPicker = false" @confirm="pickerConfirm"></u-picker>

        <u-picker :show="showShopPicker" :columns="shopList" keyName="nickName" :closeOnClickOverlay="true" @cancel="showShopPicker = false"  @confirm="shopPickerConfirm"></u-picker>

        <u-picker :show="storeShowPicker" :columns="storeColumns" keyName="name" :closeOnClickOverlay="true" @cancel="storeShowPicker = false" @close="storeShowPicker = false" @confirm="storePickerConfirm"></u-picker>
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, nextTick,watch } from 'vue';
import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app';

import { incomeList,mySummaryOfAmountForAgent,mySummaryOfAmountForPartner,merchantSummaryOfQuery,merchantList,storeOrderAmountSummary,allStoreList} from '@/api/proxy.js'

const store = useStore();


const form = ref({
    status: '',
    timeRange:'',
    partner:'',
    merchantId:'',
    searchStartTime:'',
    searchEndTime:'',
    storeId:'',
    storename:''
});
const show = ref(false);
const showPicker = ref(false);
const showShopPicker = ref(false)
const columns = ref([
    [{label:'全部',status:''},{label:'待结算',status:'0'},{label:'已结算',status:'1'}]
])
const list = ref([])
const total = ref(0)
const params = ref({
    pageNum: 1,
    pageSize: 10
})

const shopList = ref([])
const calendar = ref({
    minDate: '',
    maxDate: '',
    defaultDate: '',
    monthNum: 13,
})
const agentAmount = ref(0)
const partnerAmount = ref(0)
const merchantAmount = ref(0)
const timer = ref(null)
const storeAmount = ref(0)
const storeShowPicker = ref(false)
const storeColumns = ref([])


watch(form,(newVal,oldVal) => {
    clearTimeout(timer.value)
    timer.value = setTimeout(() => {
        params.value.pageNum = 1
        list.value = []
        getIncomeList()
        getMerchantList()
        getMerchantSummaryOfQuery()
        getStoreOrderAmountSummary() 
    },1000)
},{deep: true})

onShow(() => {
    
})

onLoad(() => {
    getIncomeList()
    chooseTimed()
    getMerchantList()
    getMerchantSummaryOfQuery()
    getStoreOrderAmountSummary()
    getAllStoreList()
    if(store?.user?.userInfo1?.roleType == 1) {
      getMySummaryOfAmountForAgent()
    } else if(store?.user?.userInfo1?.roleType == 2){
      getMySummaryOfAmountForPartner()
    }
})


onReachBottom(() => {
    if(list.value.length < total.value) {
        params.value.pageNum++;
        getIncomeList()
    }
})

const storePickerConfirm = (e) => { 
  
  console.log('confirm', e);
    
    let storeItem = storeColumns.value[0].find(item => item.id == e.value[0].id)
    console.log(storeItem)
    if(storeItem) {
        form.value.storeId = storeItem.id,
        form.value.storename = storeItem.name
    }
    storeShowPicker.value = false;
}
const getAllStoreList = () => {
    allStoreList().then(res => {
        if(res.code == 200) {
          storeColumns.value = [[{name:'全部',id:''},...res.data]]
        }
    })
}
const getStoreOrderAmountSummary = () => {
  storeOrderAmountSummary({
    searchStartTime:form.value.searchStartTime,
    searchEndTime:form.value.searchEndTime,
    storeId:form.value.storeId
  }).then(res => {
      if(res.code == 200) {
        storeAmount.value = res.data
      }
    })
}
const getMerchantSummaryOfQuery = () => { 
  merchantSummaryOfQuery({
    searchStartTime:form.value.searchStartTime,
    searchEndTime:form.value.searchEndTime,
    storeId:form.value.storeId
  }).then(res => {
      if(res.code == 200) {
        merchantAmount.value = res.data
      }
    })
}
const getMySummaryOfAmountForAgent = () => {
  mySummaryOfAmountForAgent({
    searchStartTime:form.value.searchStartTime,
    searchEndTime:form.value.searchEndTime,
    storeId:form.value.storeId
  }).then(res => {
        if(res.code == 200) {
          agentAmount.value = res.data
        }
      })
}
const getMySummaryOfAmountForPartner = () => {
  mySummaryOfAmountForPartner({
    searchStartTime:form.value.searchStartTime,
    searchEndTime:form.value.searchEndTime,
    storeId:form.value.storeId
  }).then(res => {
        if(res.code == 200) {
          partnerAmount.value = res.data
        }
      })
}
const getMerchantList = () => {
    merchantList({pageNum:1,pageSize:1000}).then(res => {
        if(res.code == 200) {
          shopList.value = [[{nickName:'全部',userId:''},...res.rows]]
        }
    }).catch(err => {
        console.log(err)
    })
}
const chooseTimed = () => {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month <= 9) {
    month = '0' + month;
    }
    if (day <= 9) {
    day = '0' + day;
    }
    let minyear = year - 1;
    calendar.value.minDate = minyear + '-' + month + '-' + day;
    calendar.value.maxDate = year + '-' + month + '-' + day;
    calendar.value.defaultDate = year + '-' + month + '-' + day;
}

const showDatePicker = () => {
    console.log('showDatePicker');
    show.value = true;
};

const timeConfirm = (e) => {
    console.log('confirm', e);
    form.value.timeRange = e[0]+'~'+e[e.length-1];
    form.value.searchStartTime = e[0] + ' 00:00:00'
    form.value.searchEndTime = e[e.length-1] + ' 23:59:59'

    show.value = false;
    
    form.value.pageNum = 1
    list.value = []
    getIncomeList()
    getMerchantSummaryOfQuery()
    getStoreOrderAmountSummary()
    if(store?.user?.userInfo1?.roleType == 1) {
      getMySummaryOfAmountForAgent()
    } else if(store?.user?.userInfo1?.roleType == 2){
      getMySummaryOfAmountForPartner()
    }
};

const pickerConfirm = (e) => {
    console.log('confirm', e);
    
    let statusItem = columns.value[0].find(item => item.status == e.value[0].status)
    console.log(statusItem)
    if(statusItem) {
        form.value.status = statusItem.label
    }
    showPicker.value = false;
};

const shopPickerConfirm = (e) => {
    console.log('confirm', e);

    let userItem = shopList.value[0].find(item => item.userId == e.value[0].userId)
    console.log(userItem)
    if(userItem) {
        form.value.merchantId = userItem.nickName
    }
    showShopPicker.value = false;
}


const getIncomeList = () => {
    let newForm = JSON.parse(JSON.stringify(form.value))
    let statusItem = columns.value[0].find(item => item.label == form.value.status)
    if(statusItem) {
         newForm.status = statusItem.status
    }

    if(shopList.value.length) {
      
      let userItem = shopList.value[0].find(item => item.nickName == form.value.merchantId)
      if(userItem) {
        newForm.merchantId = userItem.userId
      } else {
        newForm.merchantId = ''
      }
    }
   
    incomeList({...params.value,...newForm}).then(res => {
        if(res.code == 200) {
            list.value = [...list.value,...res.rows]
        }
    }).catch(err => {
        console.log(err)
    })
}

</script>

<style scoped lang="scss">
.income-record {
    .w160 {
        width:160rpx;
    }
    
    background:#F7F7F7;
    min-height:100vh;
    padding-bottom:60rpx;


    .income-total {
        background: #F8FFF8;
    }

    .shop-total {
        background: #FFFAF8;
    }

    .total-bg {
      left:0;
      bottom:0;
    }
}
</style>
